package de.gwtprime.client.widgets;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.PrimeRequestFactory;
import de.gwtprime.client.event.CommentPostedEvent;
import de.gwtprime.shared.requestFactory.ArticleCommentProxy;
import de.gwtprime.shared.requestFactory.ArticleProxy;
import de.gwtprime.shared.requestFactory.request.ArticleRequest;


public class AddCommentWidget extends Composite{

	
	interface AddCommentWidgetUiBinder extends UiBinder<Widget, AddCommentWidget>{}
	AddCommentWidgetUiBinder uiBinder = GWT.create(AddCommentWidgetUiBinder.class);
	
	@UiField TextArea commentText;
	@UiField Button saveBtn;
	
	public AddCommentWidget(final ClientFactory clientFactory, final ArticleProxy article) {
	
		
		initWidget(uiBinder.createAndBindUi(this));

		saveBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {

				final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
				final ArticleRequest request = requestFactory.articleRequest();
				
				final ArticleCommentProxy articleComment;
					articleComment = request
							.create(ArticleCommentProxy.class);
				
				articleComment.setText(commentText.getText());
				
				// clear the comments and sections because they cause a lot of lookups
				// TODO better solution?
				article.getComments().clear();
				article.getSections().clear();
				Request<Void> createReq2 = request.addCommentAndPersist(
						articleComment, clientFactory.getUser()).using(article);
				

				createReq2.fire(new Receiver<Void>() {
					@Override
					public void onSuccess(Void list) {
						System.out.println("success"); // TODO
					}

					@Override
					public void onFailure(ServerFailure error) {
						System.out.println("failed"); // TODO
					}
				});
				
				clientFactory.getEventBus().fireEvent(new CommentPostedEvent(articleComment));
			}
			
			
		});
	}
	
}
